﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MakeItWeb.Framework;
using System.Data;

namespace AllNations.WebAppAdmin
{
    public partial class RotatingBannerManager : MakeItWebAuthenticatedUserPage
    {
        protected override void OnInitComplete(EventArgs e)
        {
            base.OnInitComplete(e);
            if (!IsInRole("HomepageImageManager"))
                throw new System.Security.SecurityException();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                RefreshImages();
                hidRotatingBannerId.Value = Guid.NewGuid().ToString();
            }
            RegisterAdminFunction("Add new banner", "javascript:ShareNewFile();void(0);", "~/Images/btn-plus.gif");
        }

        protected void btSaveNewFile_Click(object sender, EventArgs e)
        {
            if (IsPageAdministrator() && fuNewFile.UploadedFiles.Count > 0)
            {
                try
                {
                    lblErrorMesg.Text = string.Empty;

                    Guid guidRotatingBannerId = new Guid(hidRotatingBannerId.Value);

                    fuNewFile.UploadedFiles[0].SaveAs(string.Format(@"{0}\{1}", Server.MapPath("~/Images/Main"), fuNewFile.UploadedFiles[0].FileName), true);

                    StoredProcArgs args = new StoredProcArgs();
                    args["pRotatingBannerId"] = guidRotatingBannerId;
                    args["pImageFilenameTxt"] = fuNewFile.UploadedFiles[0].FileName;
                    args["pNavigationUrl"] = txtNavigationUrl.Text.Trim();
                    GenericCud.ExecuteCud("proc_cm_SaveRotatingBanner", args);

                    RefreshImages();
                    txtNavigationUrl.Text = string.Empty;
                    hidRotatingBannerId.Value = Guid.NewGuid().ToString();
                }
                catch (Exception ex)
                {
                    lblErrorMesg.Text = string.Format("Error saving new file: {0}", ex.Message);
                    panelAddNewFile.Style["display"] = "block";
                }
            }
        }

        protected bool IsLastItem(object oPriorityNum)
        {
            var ds = rptRotatingImage.DataSource as DataSet;
            var lastRow = (from row in ds.Tables[0].Select()
                           select row).OrderByDescending(s => s["priority_num"]).FirstOrDefault();
            return (int)lastRow["priority_num"] == (int)oPriorityNum;
        }

        private void RefreshImages()
        {
            rptRotatingImage.DataSource = GenericQry.GetDataSet("proc_cm_ListRotatingBanner", new StoredProcArgs());
            rptRotatingImage.DataBind();
        }

        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            Guid guidRotatingImageId = new Guid((sender as LinkButton).CommandArgument);
            StoredProcArgs args = new StoredProcArgs();
            args["pRotatingBannerId"] = guidRotatingImageId;
            using (DataSet ds = GenericQry.GetDataSet("proc_cm_GetRotatingBanner", args))
            {
                if (ds.Tables[0].Rows.Count == 0)
                    return;

                try
                {
                    string sFilename = string.Format(@"{0}\{1}", Server.MapPath("~/Images/Main"), ds.Tables[0].Rows[0]["image_filename_txt"]);
                    System.IO.File.Delete(sFilename);
                }
                catch { }

                GenericCud.ExecuteCud("proc_cm_DeleteRotatingBanner", args);

                RefreshImages();
            }
        }

        protected void MoveImagesClick(object sender, EventArgs e)
        {
            var button = sender as LinkButton;
            var guidRotatingImageId = new Guid(button.CommandArgument);
            var storedProc = button.CommandName == "MoveUp" ? "proc_cm_MoveUpRotatingBanner" : "proc_cm_MoveDownRotatingBanner";
            StoredProcArgs args = new StoredProcArgs();
            args["pRotatingBannerId"] = guidRotatingImageId;

            GenericCud.ExecuteCud(storedProc, args);

            RefreshImages();
        }
    }
}